import { isArray } from '@src/util/type';
/* model */
import { OpenDataToolTip } from "@model/types/OpenData"
import Log from "@src/util/log"
/* util */
import { isFunction, isNumber } from "@src/util/type"

type OpenDataItemResult = { items: { data: string }[] }

const LEFT_BRACKET: string = '['
const RIGHT_BRACKET: string = ']'
const VERTICAL_BAR: string = '|'
const NULL_STRING: string = 'null'

// example: [大海|DaHai]自定义异常了工单#TNK0121090010
export function formattedOpenDataTooltip(tooltip: string): OpenDataToolTip[] {
  let char: string = ''
  let openDataToolTipList: OpenDataToolTip[] = []
  let bracket: string = ''
  let leftBracketIndex: number | null = null
  let tempText: string = ''
  
  for (let i = 0; i < tooltip.length; i++) {
    char = tooltip[i]
    
    if (char === LEFT_BRACKET) {
      openDataToolTipList.push({ text: tempText  })
      leftBracketIndex = i
      tempText = ''
    }
    else if (char === RIGHT_BRACKET) {
      bracket = tooltip.substr(Number(leftBracketIndex) + 1, i - 1)
      openDataToolTipList = openDataToolTipList.concat(formattedOpenDataTooltipBracket(bracket))
      leftBracketIndex = null
    }
    else if (!isNumber(leftBracketIndex)) {
      tempText += char
    }
  }
  
  if (tempText) {
    openDataToolTipList.push({ text: tempText  })
  }
  
  return openDataToolTipList
}

function formattedOpenDataTooltipBracket(str: string): OpenDataToolTip[] {
  const filteredStr: string = str.replace(LEFT_BRACKET, '').replace(RIGHT_BRACKET, '').replace(/null/g, '')
  const list: string[] = filteredStr.split(VERTICAL_BAR)
  const userNames: string[] = list[0]?.split(',') || []
  const staffIds: string[] = list[1]?.split(',') || []
  
  return (
    userNames.map((userName, index) => {
      return {
        userName,
        staffId: staffIds[index] || ''
      }
    })
  )
}

async function openDataCanvasConvertData(data: any[], staffIdKey: string, userNameKey: string) {
  
  if (!isFunction(window?.WWOpenData?.prefetch)) {
    return data
  }
  
  if (!isArray(data)) {
    return data
  }
  
  if (window.WWOpenData?.initCanvas) {
    window.WWOpenData.initCanvas()
    window.WWOpenData.enableCanvasSharing()
  }
  
  try {
    
    let result: any[] = []
    
    const staffIds: string[] = data.map(item => item?.[staffIdKey] ?? '')
    const openDataItems = staffIds.map(staffId => {
      return {
        type: 'userName',
        id: staffId
      }
    })
    
    const openDataResult: OpenDataItemResult = await new Promise((resolve, reject) => {
      
      window.WWOpenData?.prefetch(
        { items: openDataItems }, 
        (err: unknown, data: OpenDataItemResult) => {
          
          if (err) {
            return reject(err)
          }
          
          resolve(data)
        }
      )
      
    })
    
    result = data.map((item, index) => {
      return Object.assign({}, item, { [userNameKey]: openDataResult.items[index].data })
    })
    
    return result
    
  } catch (error) {
    Log.error(error, openDataCanvasConvertData.name)
    return data
  }
  
}

export {
  openDataCanvasConvertData
}